﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using StackExchange.Redis;
using Xwy.Practical.Utils;

namespace Xwy.Practical.Controllers
{
    public class RedisController : Controller
    {
        private readonly IDistributedCache _distributeCache;
        private readonly IDatabase _redis;
        public RedisController(RedisService client, IDistributedCache distributeCache)
        {
            _distributeCache = distributeCache;
            _redis = client.GetDatabase();
        }

        public async Task<IActionResult> Index()
        {
            _redis.StringSet("TestRedis", "11111");
            string temp = await _redis.StringGetAsync("TestRedis");
            ViewBag.Temp = temp;

            
            string key = "NowTime";
            string value = await _distributeCache.GetStringAsync(key);
            if (value == null)
            {
                value = "redis time:" + DateTime.Now.ToString();
                DistributedCacheEntryOptions cacheEntryOptions = new DistributedCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(15)
                };
                await _distributeCache.SetStringAsync(key, value, cacheEntryOptions);//15秒后过期        
                await _distributeCache.SetStringAsync(key+"222", value, cacheEntryOptions);//15秒后过期     
            }
            ViewBag.NowTime = value;


            return View();
        }      
    }


}